import { ChatRequest, ChatResponse, KnowledgeBase, DocumentResponse } from '../types/chat';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

export const chatApi = {
  async sendMessage(request: ChatRequest): Promise<ChatResponse> {
    const response = await fetch(`${API_BASE_URL}/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error('Failed to send message');
    }

    return response.json();
  },

  async sendMessageStream(
    request: ChatRequest,
    onChunk: (chunk: string) => void
  ): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ...request, stream: true }),
    });

    if (!response.ok) {
      throw new Error('Failed to send message');
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('Failed to get response reader');
    }

    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');
      
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const content = line.slice(6);
          onChunk(content);
        }
      }
    }
  },

  async getKnowledgeBases(): Promise<KnowledgeBase[]> {
    const response = await fetch(`${API_BASE_URL}/knowledge-bases`);
    
    if (!response.ok) {
      throw new Error('Failed to get knowledge bases');
    }

    return response.json();
  },

  async uploadDocument(
    file: File,
    name?: string,
    description?: string
  ): Promise<DocumentResponse> {
    const formData = new FormData();
    formData.append('file', file);
    if (name) formData.append('name', name);
    if (description) formData.append('description', description);

    const response = await fetch(`${API_BASE_URL}/upload`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error('Failed to upload document');
    }

    return response.json();
  },

  async deleteKnowledgeBase(documentId: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/knowledge-bases/${documentId}`, {
      method: 'DELETE',
    });

    if (!response.ok) {
      throw new Error('Failed to delete knowledge base');
    }
  },
}; 